#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket
import sys
import time
import base64
import random
import string
import displayChart  #display the data well
def show_except_socket(e):
    print 'Error close socket:%s' % e
    
def close_socket(sockobj) :
    try:
        sockobj.close()  
    except socket.error, e :    
        show_except_socket(e)

def check(args):#switch,points,frequence
    if len(args) < 3:return False
    if args[0] != 0 and args[0] != 1:
        return False
    if args[1] < 1 or args[1] > 200:
        return False
    if args[2] < 6 or args[2] > 60:
        return False
    return True

def receive_msg(sockobj):
    buf = ''
    while True:
        try:
            buf = sockobj.recv(1024)
        except socket.error,e:
            show_except_socket(e)
            close_socket(sockobj)
        if not len(buf) or buf == '':
            #print 'Socket closed'
            #close_socket(sockobj)
            #break
            continue
        else:
            break
    if not len(buf):return ''
    else:return buf

def display(res,ti,sttime):#display the result well
    displayChart.display_val_time(res,ti,sttime)



def verify_str(ver_data):

    print ver_data

    s1 = base64.encodestring(ver_data)
    print 's1:',s1
    salt = ''
    for i in range(0,4):
        salt += chr(random.randint(0,25)+ord('A'))
    s2 = salt+s1+salt #salt is random str
    s2 = base64.encodestring(str(s2))

    print 's2:',s2
    return s2


'''
the process: get test info --> send info about the verification --> get the ACK --> send the command --> get the ACK
--> receive the sensor data
'''
def commu(sockobj):
    #verfication:get test info

    buf =  receive_msg(sockobj)
    if buf == '':
        print 'fail to get the verification msg'
        return

    #send info about the verification
    data = verify_str(buf)
    try:
        sockobj.send(data)
        print data,'sending OK!'
    except socket.error,e:
        show_except_socket(e)
        close_socket(sockobj)
        return
    buf =  receive_msg(sockobj)
    if buf == '' or buf != 'ACK':
        print 'fail to pass the verification'
        return

    print 'receiving:',buf

    #send the command
    #TODO:change the sending data here

    switch = 1;points = 7;frequence = 2
    #the data to be sent:on/off,x points,frequence sampling interval
    command = "switch="+str(switch)+"&"+"points="+str(points)+"&"+"frequence="+str(frequence)
    # while check([switch,points,frequence]) == False:
    #     print 'enter the parameter:'
    #     switch = int(raw_input('switch<1/0>:'))
    #     points = int(raw_input('points<1,200>:'))
    #     frequence = int(raw_input('frequence<6,60>seconds:'))
    # command = "switch="+str(switch)+"&"+"points="+str(points)+"&"+"frequence="+str(frequence)

    print 'sending command:',command

    try:
        sockobj.send(command)
        print command,'sending OK!'
    except socket.error,e:
        show_except_socket(e)
        close_socket(sockobj)
        return



    #receive ACK
    buf =  receive_msg(sockobj)
    print 'buf:'+buf
    #Sending command ok, now receive the data from the server
    if buf != 'ACK':
        print 'Haven\'t got the ACK from the server!\nFail to send the command';close_socket(sockobj);return
    if switch == 0:
        print 'turn off the sensor';close_socket(sockobj);return
    #receive the ACK msg and switch on the device
    print 'receiving sensor data...'
    res = [];ti = []
    sttime = time.strftime("%Y/%m/%d",time.localtime())
    for i in range(0,points):#TODO:get the result from the sensor and display it well
        #tp = float(receive_msg(sockobj))
        tp = string.atof(receive_msg(sockobj))
        res.append(tp)
        ti.append(time.strftime('%H:%M:%S',time.localtime()))
        print tp
        time.sleep(frequence)
    close_socket(sockobj)
    display(res,ti,sttime)


if __name__ == '__main__':
    print len(sys.argv)
    if len(sys.argv) == 3 and sys.argv[1] != None and sys.argv[2] != None:
        print sys.argv[1],sys.argv[2]
    else:
        print 'Usage:python client_socket.py <IP> <port>'
        sys.exit(-1)


    # ss = verify_str()

    # verify(ss,socket.gethostbyname(socket.gethostname()))

    server_host = sys.argv[1]
    server_port = int(sys.argv[2])
    print "Start client"
    sockobj = ''


    sockobj = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockobj.connect((server_host,server_port))
    commu(sockobj)




